HackerRank Matrix Layer Rotation
解答
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'matrixRotation' function below.
#
# The function accepts following parameters:
# 1. 2D_INTEGER_ARRAY matrix
# 2. INTEGER r
#
def matrixRotation(matrix, r):
# Write your code here
# temporary matrix
mat = []
k = min(m,n) // 2 # compute no. of layers
# to get elements from the layer
for i in range(k):
temp = []
# a11 - a14
for j in range(i, n-1-i): # -i: to reduce layer
# a15 - a35
for j in range(i, m-1-i):
# a45 - a42
for j in range(n-1-i, i, -1):
# a41 -a21
for j in range(m-1-i, i, -1):
mat.append(temp)
# rotate elements and place it in original matrix
for i in range(k):
# find index after rotation
idx = r % len(row)
def inc():
return (idx + 1) % len(row)
for j in range(i, n-1-i): # -i: to reduce layer
idx = inc()
for j in range(i, m-1-i):
idx = inc()
for j in range(n-1-i, i, -1):
idx = inc()
for j in range(m-1-i, i, -1):
idx = inc()
# print the matrix
for row in matrix:
print(*row)
if __name__ == '__main__':
first_multiple_input = input().rstrip().split()
m = int(first_multiple_input0) n = int(first_multiple_input1) r = int(first_multiple_input2) matrix = []
for _ in range(m):
matrix.append(list(map(int, input().rstrip().split())))
matrixRotation(matrix, r)
メモ
https://www.youtube.com/watch?v=acGcfh4JJiI